//
//  RPNCalcBRAIN.m
//  RPNCalc
//
//  Created by Jacob V.V. Goldberg on 6/26/12.
//  Copyright (c) 2012 FutureSight Technologies. All rights reserved.
//

#import "RPNCalcBRAIN.h"

//begin interface
@interface RPNCalcBRAIN()
@property (nonatomic, strong) NSMutableArray *operandStack;
@end

//begin the real code, let's get this party started!
@implementation RPNCalcBRAIN
@synthesize operandStack = _operandStack;

-(NSMutableArray *) operandStack {
    if (_operandStack == nil) {
        _operandStack = [[NSMutableArray alloc] init];
        return _operandStack;
    } else {
        return _operandStack;
    }
}

-(void) pushOperand:(double)operand {
    [self.operandStack addObject:[NSNumber numberWithDouble:operand]];
}

-(double) popOperand {
    NSNumber *operandObject = [self.operandStack lastObject];
    if (operandObject) {
        [self.operandStack removeLastObject];
    }
    return [operandObject doubleValue];
}

-(double) performOperation:(NSString *)operation {    
    double result = 0;
            
    double v1, v2;
    if (![operation isEqualToString:@"π"]) {
        v2 = [self popOperand];
        v1 = [self popOperand];
    } else {
        result = 3.1415926535897932384626433832795028841971693993751058209749;
    }
    
    if ([operation isEqualToString:@"+"]) {
        result = v1 + v2;
    } else if ([operation isEqualToString:@"-"]) {
        result = v1 - v2;
    } else if ([operation isEqualToString:@"X"]) {
        result = v1 * v2;
    } else if ([operation isEqualToString:@"÷"]) {
        result = v1 / v2;
    } else if ([operation isEqualToString:@"^"]) {
        result = pow(v1, v2);
    } else if ([operation isEqualToString:@"x√"]) {
        result = pow(v2, 1/v1);
    }
    return result;
}

-(void) eraseAllOperands {
    [self.operandStack removeAllObjects];
}

@end